//
//  SHStatusPictureView.swift
//  SHWeibo3
//
//  Created by teacher on 16/7/25.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit
// cell 可重用表示符
private let SHStatusPictureViewCellId = "SHStatusPictureViewCell"
// cell间距
let cellMargin: CGFloat = 5
// cell宽高
let cellWH: CGFloat = 80
class SHStatusPictureView: UICollectionView {
    // 创建一个模型
    var pictureInfo: [SHPictureInfo]?{
        didSet{
            // countLabel赋值
            countLabel.text = "\(pictureInfo?.count ?? 0)"
            // 获得当前配图的size
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            // 更新当前配图的约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新UI
            reloadData()
        }
    }
    
    // 计算配图的size
    func getPictureViewSize(count: Int) -> CGSize{

        // 计算出行数和列数
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        // 计算size 中的宽和高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1)*cellMargin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMargin
        
        
        return CGSize(width: w, height: h)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.clearColor()
        // 获取layout
        let layout = self.collectionViewLayout as!UICollectionViewFlowLayout
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置水平和垂直间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        // 注册cell
        registerClass(SHStatusPictureViewCell.self, forCellWithReuseIdentifier: SHStatusPictureViewCellId)
        // 设置数据源代理
        dataSource = self
        delegate = self
        // 添加控件
        addSubview(countLabel)
        
        // 添加约束
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    
    
    // MARK: -  懒加载
    // count
    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), textFont: 35)
    

}

extension SHStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfo?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SHStatusPictureViewCellId, forIndexPath: indexPath) as! SHStatusPictureViewCell
        // cell赋值
        cell.pic_url = pictureInfo![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
//        photoBrowser.delegate = self;
//        photoBrowser.currentImageIndex = indexPath.item;
//        photoBrowser.imageCount = self.modelsArray.count;
//        photoBrowser.sourceImagesContainerView = self.collectionView;
//        
//        [photoBrowser show];
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        // 当前选中图片
        photoBrowser.currentImageIndex = indexPath.item
        // 总图数
        photoBrowser.imageCount = pictureInfo!.count
        // 父控件
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    
    }
}

extension SHStatusPictureView: SDPhotoBrowserDelegate {
    // 小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
//        SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
//        
//        return cell.imageView.image;
        
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! SHStatusPictureViewCell
        return cell.bgImageView.image
    }
    // 高清图
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
//        NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
//        return [NSURL URLWithString:urlStr];
        var urlStr = pictureInfo![index].thumbnail_pic!
        urlStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
        
    }
}

// 自定义cell
class SHStatusPictureViewCell: UICollectionViewCell {
    // 定义一个模型 供外界赋值
    var pic_url: SHPictureInfo?{
        didSet{
            // 设置image
            bgImageView.sh_setImage(pic_url?.thumbnail_pic, placeholderImgName: "weibo_placeholder")
            // 判断是否为nil 而且后缀为gif （考虑到cell复用问题）
            if let thPic = pic_url?.thumbnail_pic where thPic.hasSuffix(".gif"){
                gifImageView.hidden = false
            }else {
                gifImageView.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 设置视图
    private func setupUI(){
        //backgroundColor = RandomColor()
        // 01 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        // 02 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    // 背景图片
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(imgName: "weibo_placeholder")
        img.contentMode = .ScaleAspectFill
        img.layer.masksToBounds = true
        return img
    }()
    
    // 动态图片logo
    private lazy var gifImageView: UIImageView = UIImageView(imgName: "timeline_image_gif")
    
    
}











